package day4.demo2_可重入锁;

import java.util.Scanner;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Shop implements Runnable{
    int num = 10;
    String mode;
    Lock lock = new ReentrantLock();


    @Override
    public void run() {
        Scanner in = new Scanner(System.in);
        System.out.println("请输入"+ Thread.currentThread().getName()+"要执行的操作，b表示购物，否则其他键表示查询库存");
        mode = in.next();
        if(mode.equals("b")){
            buylock();
        }else {
            getNumlock();
        }
    }
    synchronized void buy(){
        num--;
        System.out.println(Thread.currentThread().getName()+"成功购买一件商品，接下来查询剩余商品数量。。。");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {}
        getNum();
    }

    synchronized void getNum() {
        System.out.println(Thread.currentThread().getName()+"查询到当前库存："+num);
    }

    void buylock(){
        try{
            lock.lock();
            num--;
            System.out.println(Thread.currentThread().getName()+"成功购买一件商品，接下来查询剩余商品数量。。。");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {}
            getNum();
        }finally {
            lock.unlock();
        }

    }

    void getNumlock() {
        try{
            lock.lock();
            System.out.println(Thread.currentThread().getName()+"查询到当前库存："+num);

        }finally {
            lock.unlock();
        }
    }
}
